package com.proscenic.oauth2.server.service.impl;

import com.proscenic.common.web.vo.Result;
import com.proscenic.oauth2.server.service.IndexService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.security.oauth2.core.ClientAuthenticationMethod;
import org.springframework.security.oauth2.core.oidc.OidcScopes;
import org.springframework.security.oauth2.server.authorization.client.JdbcRegisteredClientRepository;
import org.springframework.security.oauth2.server.authorization.client.RegisteredClient;
import org.springframework.security.oauth2.server.authorization.config.ClientSettings;
import org.springframework.security.oauth2.server.authorization.config.TokenSettings;
import org.springframework.stereotype.Service;

import java.util.UUID;


/**
 * @version 1.0
 * created by chenxin on 2022/3/7 19:30
 */
@Service
public class IndexServiceImpl implements IndexService {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public Result registerClient(){
        RegisteredClient client = RegisteredClient
                .withId(UUID.randomUUID().toString())
                .clientId("My Life+")
                .clientSecret("secret")
                .clientName("My Life+")
                //授权方法
                .clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_JWT)
                //授权类型
                .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
                .redirectUri("http://127.0.0.1:8080/authorized")
                //OIDC支持
                .scope(OidcScopes.OPENID)
                .scope("read")
                //JWT的配置项
                .tokenSettings(TokenSettings.builder().build())
                //客户端配置项
                .clientSettings(ClientSettings.builder().requireAuthorizationConsent(true).build())
                .build();

        JdbcRegisteredClientRepository repository = new JdbcRegisteredClientRepository(jdbcTemplate);
        if(repository.findByClientId(client.getClientId()) == null){
            repository.save(client);
        }

        return Result.success(null);
    }
}
